package net.valerijtimakov.homefinances.dao.storages.common.mysql.query_builders;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MultiInsertQuery extends InsertQuery {
	
	private List<Map<String, Object>> fieldValues;
	private Set<String> fieldNames;
	private boolean fieldNamesInited = false;
	
	public MultiInsertQuery() {
		super();
	}

	public MultiInsertQuery(String tableName) {
		setTableName(tableName);
		fieldValues = new ArrayList<Map<String, Object>>();
		fieldNames = new HashSet<String>();
	}
	
	public Map<String, Object> addItem() {
		fieldNamesInited = false;
		Map<String, Object> item = new HashMap<String, Object>();
		fieldValues.add(item);
		return item;
	}
	
	@Override
	protected Set<String> getFieldNamesSet() {
		if (!fieldNamesInited) {
			for (Map<String, Object> valItem : fieldValues) {
				for (String fName : valItem.keySet()) {
					fieldNames.add(fName);
				}
			}
			fieldNamesInited = true;
		}
		return fieldNames;
	}

	@Override
	protected StringBuilder getFieldValuesLine() {
		StringBuilder res = new StringBuilder();
		for (Map<String, Object> fieldValue : fieldValues) {
			StringBuilder itemSb = new StringBuilder();
			for (String fieldName : getFieldNamesSet()) {
				if (itemSb.length() != 0) {
					itemSb.append(",");
				}
				itemSb.append(MySqlUtils.getValueLine(fieldValue.get(fieldName)));
			}
			if (res.length() > 0) {
				res.append(",");
			}
			res.append("(");
			res.append(itemSb);
			res.append(")");
		}
		return res;
	}
	
}
